import type { RouteObject } from 'react-router-dom';
import { Link, Outlet, useParams, useRoutes } from 'react-router-dom';

import { Layout } from '@/components';

interface RouterAuth extends RouteObject {
  auth?: string;
  children?: RouterAuth[];
}

const App = () => {
  const routes: RouterAuth[] = [
    {
      path: '/',
      element: <Layout />,
      children: [
        { index: true, element: <Home /> },
        {
          path: '/courses',
          element: <Courses />,
          auth: 'courses',
          children: [
            { index: true, element: <CoursesIndex /> },
            { path: '/courses/:id', element: <Course /> },
          ],
        },
        { path: '*', element: <NoMatch /> },
      ],
    },
  ];

  const element = useRoutes(routes);

  return <div>{element}</div>;
};

function Home() {
  return (
    <div>
      <h2>Home</h2>
    </div>
  );
}

function Courses() {
  return (
    <div>
      <h2>Courses</h2>
      <Outlet />
    </div>
  );
}

function CoursesIndex() {
  return (
    <div>
      <p>Please choose a course:</p>

      <nav>
        <ul>
          <li>
            <Link to="react-fundamentals">React Fundamentals</Link>
          </li>
          <li>
            <Link to="advanced-react">Advanced React</Link>
          </li>
          <li>
            <Link to="react-router">React Router</Link>
          </li>
        </ul>
      </nav>
    </div>
  );
}

function Course() {
  const { id } = useParams<'id'>();

  return (
    <div>
      <h2>Welcome to the {id!.split('-').map(capitalizeString).join(' ')} course!</h2>

      <p>This is a great course. You're gonna love it!</p>

      <Link to="/courses">See all courses</Link>
    </div>
  );
}

function capitalizeString(s: string): string {
  return s.charAt(0).toUpperCase() + s.slice(1);
}

function NoMatch() {
  return (
    <div>
      <h2>It looks like you're lost...</h2>
      <p>
        <Link to="/">Go to the home page</Link>
      </p>
    </div>
  );
}

export default App;
